<template>
  <div class="container">
    <div id="mapDiv"></div>
    <div class="btns" v-if="!visible">
      <a-button style="margin-right: 60px; background-color: #4172b2; color: #fff" @click="SimulatedFloodControlOperation()">防洪调度模拟</a-button>
      <a-button style="background-color: #4172b2; color: #fff" @click="uploadFloodData">下载洪水数据</a-button>
    </div>
    <a-modal title="防洪调度模拟" v-model="visible">
      <div class="CenterContentPart" style="flex-direction: row; border-bottom: none">
        <!-- select 框是由input和下拉框组成, 这里v-model 绑定input的框的初始值, 当我选择下拉选项的时候 -->
        <!-- v-model 会拿到select 给他的value 和 应该显示的label -->
        <a-select style="width: 156px" @change="handleChange" v-model="selectValueDefaultLabel">
          <a-select-option value="201907">2019年7月洪水</a-select-option>
          <a-select-option value="202006">2020年6月洪水</a-select-option>
          <a-select-option value="202106">2021年6月洪水</a-select-option>
        </a-select>
        <a-button type="primary" @click="uploadThreeFullyData" style="margin-left: 20px">下载3小时内完整数据</a-button>
      </div>
      <div class="CenterContentPart">
        <div style="font-size: 20px; margin-bottom: 10px">基本信息</div>
        <div class="basisWord" style="white-space: pre-line; text-align: left">
          {{ floodControlOperation.content }}
        </div>
      </div>
      <div class="CenterContentPart" style="margin-top: 10px">
        <div class="ContentLayout" v-for="(item, index) in floodControlOperation.riverList" :key="index" style="margin-top: 10px">
          <div class="" v-if="index == 0">
            预测{{ item.name }}1小时后流量达到 :
            <a-input-number style="margin: 0 10px" :min="0" :max="990000" v-model="floodControlOperation.riverList[index].value" @change="predictFlowChange" />
            <span style="width: 110px; text-align: right"> 立方米</span>
          </div>
          <div class="" v-else>
            {{ item.name }}&nbsp;&nbsp; : &nbsp;&nbsp;拦截流量
            <a-input-number style="margin: 0 10px" :min="0" :max="30" v-model="floodControlOperation.riverList[index].value" @change="riverFlowChange" />
            <span style="color: red; width: 110px; text-align: right">上限{{ item.limited }} 立方米</span>
          </div>
        </div>
        <div style="margin-top: 10px">
          已经使用总调度的:
          <span style="font-size: 22px; font-weight: 550">{{ occupyTotally }}%</span>
        </div>
        <a-button type="primary" style="margin-top: 10px" @click="emulateTest">模拟调度</a-button>
      </div>
      <div class="CenterContentPart" style="margin-top: 20px">
        <p>
          <!-- TODO: -->
          拦截前流量为 {{preBlockFlow}}立方米 上述调度方案执行后, 1小时后缙云河道减少掉的流量为:<span style="color: red">{{ reduceVolume }}</span>立方米,
          实际流量为
        </p>
        <div v-if="!resultAllow && resultVolume != 0" class="warnWord">
          <div class="warnDescription">
            {{ resultVolume }}
            <span style="color: red; font-size: 30px; font-weight: 550">立方米</span>
          </div>
          <span style="color: red; font-size: 22px; margin-bottom: 20px">
            已经超出了警戒线
          </span>

          <span>河道流量上限为{{ limitedVolume }}立方米</span>
        </div>
        <div v-else class="success">
          <span style="color: #000; font-size: 22px; margin-bottom: 20px">{{
            resultVolume == 0 ? "暂未模拟" : ""
          }}</span>
          <span style="font-size: 20px" v-show="resultVolume == 0">河道流量上限为{{ limitedVolume }}立方米</span>
          <span style="color: #2ecc71; font-size: 30px; font-weight: 550" v-show="resultVolume != 0">{{ resultVolume }}立方米</span>
          <span style="color: #2ecc71; font-size: 28px; font-weight: 550" v-show="resultVolume != 0">尚未超过上限{{ limitedVolume }}立方米</span>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
/* */
// import "../assets/mapApi";
// import "../assets/HeatmapOverlay"
var map = [];
var data = [
  { name: "缙云仙都", value: 0 },
  { name: "缙云仙都2", value: 0 },
  { name: "缙云仙都3", value: 0 },
];
var geoCoordMap = {
  缙云仙都: [120.09921, 28.66041],
  缙云仙都2: [120.09749, 28.64843],
  缙云仙都3: [120.08118, 28.65444],
};
var heatmapOverlay; //热力图覆盖物
export default {
  data() {
    return {
      preBlockFlow:0,
      showHeatMap: false, //显示热力图的标志
      HeatMapValue: 0, // 显示热力图的数值
      occupyTotally: 0, //占据总额的百分比
      timeDate: 202106, //在select框变化时 拿到value 用于下载数据
      reduceVolume: 0,
      resultAllow: true, // 最后是否允许(超过警戒线)
      resultVolume: 0, // 最后为多少立方米
      limitedVolume: 250, // 河流上限为多少立方米
      visible: false, // 模态可见
      floodControlOperation: {
        content: " ",
        riverList: [
          {
            name: "缙云河道", // 河道名称
            intercept: "xxx", // 拦截流量
            value: 0,
            limited: 0,
          },
          {
            name: "壶镇河道", // 河道名称
            intercept: "xxx", // 拦截流量
            value: 0,
            limited: 0,
          },
          {
            name: "东方河道", // 河道名称
            intercept: "xxx", // 拦截流量
            value: 0,
            limited: 0,
          },
          {
            name: "仙都河道", // 河道名称
            intercept: "xxx", // 拦截流量
            value: 0,
            limited: 0,
          },
        ],
      },
      rainData: [],
      riverData: [],
      selectValueDefaultLabel: "2021年6月洪水", //控制初始化selectValue的初始化显示文字
    };
  },

  mounted() {
    var points = this.convertData(data);
    console.log(points);
    map = new T.Map("mapDiv", {
      projection: "EPSG:4326",
    });

    this.initMapTools(map);
    this.initShowIcon();
    // map = new T.Map('mapDiv');
    heatmapOverlay = new T.HeatmapOverlay({
      opacity: 0,
      radius: 150,
      gradient: {
        0.2: "#E74C3C",
        0.5: "#EC7063",
        0.8: "#E74C3C",
      },
    });
    map.addOverLay(heatmapOverlay);
    heatmapOverlay.setDataSet({ data: points, max: 500 });
    // heatmapOverlay.show();
  },

  methods: {
    convertData(data) {
      var res = [];
      for (var i = 0; i < data.length; i++) {
        var geoCoord = geoCoordMap[data[i].name];
        if (geoCoord) {
          res.push({
            name: data[i].name,
            lat: geoCoord[1],
            lng: geoCoord[0],
            count: data[i].value,
          });
        }
      }
      return res;
    },
    async emulateTest() {
      let params = {};
      params.date = this.timeDate;
      params.predictFlow = this.floodControlOperation.riverList[0].value;
      params.dfBlockingFlow = this.floodControlOperation.riverList[2].value;
      params.hzBlockingFlow = this.floodControlOperation.riverList[1].value;
      params.xdBlockingFlow = this.floodControlOperation.riverList[3].value;
      const { data: res } = await this.$http.post("/api/emulation/doemulate", {
        ...params,
      });
      this.reduceVolume = res.data.reduceFlow.toFixed(2); //
      this.resultVolume = res.data.actFlow.toFixed(2); // 警戒线250
      this.preBlockFlow = res.data.preBlockFlow;
      console.log("本次的防洪调度数据", this.resultVolume);

      if (this.resultVolume > 250) {
        this.resultAllow = false;
        // this.showHeatMap = true;
        data = data.map((item) => {
          item.value = Number(this.resultVolume);
          return item;
        });
        var points = this.convertData(data);
        heatmapOverlay.setDataSet({ data: points, max: 500 });
      } else {
        this.resultAllow = true;
        // this.showHeatMap = false;
        data = data.map((item) => {
          item.value = 0;
          return item;
        });
        var points = this.convertData(data);
        heatmapOverlay.setDataSet({ data: points, max: 500 });
      }
    },
    predictFlowChange(value) {},
    riverFlowChange(value) {
      // console.log(value)
      if (value > 30) {
        this.common.notify("warning", "当前值超过最大额度,将为你设置最大值");
      }
      let sum = 0;
      this.floodControlOperation.riverList.map((item, index) => {
        if (index != 0) {
          if (item.value > 30) {
            sum += 30;
          } else {
            sum += item.value;
          }
        }
      });
      this.occupyTotally = ((sum / 90) * 100).toFixed(2);
    },
    // 设置初始的比例尺之类的相关信息
    initMapTools(map) {
      var zoom = 12;
      map.centerAndZoom(new T.LngLat(120.19112, 28.74683), zoom);
      // 创建比例尺控件对象
      var scale = new T.Control.Scale();
      // 添加比例尺控件
      map.addControl(scale);
      // 创建对象


      var ctrl = new T.Control.MapType([
            {
          title: "卫星混合",
          icon: "http://api.tianditu.gov.cn/v4.0/image/map/maptype/satellitepoi.png",
          layer: TMAP_HYBRID_MAP,
        },
          {
          title: "卫星",
          icon: T.Icon.Default.imagePath + "/map/maptype/satellite.png",
          layer: TMAP_SATELLITE_MAP,
        },
        {
          title: "地形",
          icon: T.Icon.Default.imagePath + "/map/maptype/terrain.png",
          layer: TMAP_TERRAIN_MAP,
        },
        {
          title: "地形混合",
          icon: T.Icon.Default.imagePath + "/map/maptype/terrainpoi.png",
          layer: TMAP_TERRAIN_HYBRID_MAP,
        },
        {
          title: "地图", //地图控件上所要显示的图层名称
          icon: "http://api.tianditu.gov.cn/v4.0/image/map/maptype/vector.png",
          layer: TMAP_NORMAL_MAP, //地图类型对象，即MapType。
        },
      ]);
        // map.addControl(window.TMAP_HYBRID_MAP)
      map.addControl(ctrl);
             map.addControl(window.TMAP_HYBRID_MAP)

    
      // 创建缩放平移控件对象
      var control = new T.Control.Zoom();
      // 添加缩放平移控件
      map.addControl(control);
      map.addEventListener("click", this.closeChart);
    },
    // 查询后端 拿到站点信息
    async initShowIcon() {
      const { data: res } = await this.$http.get(`/api/rainfallstation/list`);
      this.rainData = res.data;
      const { data: res2 } = await this.$http.get(
        `/api/rivergatewaystation/list`
      );
      this.riverData = res2.data;
      this.initOverlay(map);
    },
    // 添加图标注释
    initOverlay(map) {
      // 注册雨量站的图标
      const rain = new T.Icon({
        iconUrl: "https://s1.xptou.com/2022/11/28/6384b1b09c25e.png",
        iconSize: new T.Point(28, 32),
        iconAnchor: new T.Point(10, 25),
      });
      // 向地图上添加自定义标注
      this.rainData.map((item) => {
        // console.log("data",item.longitude,item.latitude)
        var marker = new T.Marker(new T.LngLat(item.longitude, item.latitude), {
          icon: rain,
        });
        map.addOverLay(marker);
        marker.addEventListener("click", this.handleClickRain);
      });
      // console.log(this.riverData)
      const river = new T.Icon({
        iconUrl: "https://s1.xptou.com/2022/11/28/6384ae55af160.png",
        iconSize: new T.Point(28, 32),
        iconAnchor: new T.Point(10, 25),
      });
      this.riverData.map((item) => {
        // console.log("data",item.longitude,item.latitude)
        var marker2 = new T.Marker(
          new T.LngLat(item.longitude, item.latitude),
          {
            icon: river,
          }
        );
        map.addOverLay(marker2);
        marker2.addEventListener("click", this.handleClickRiver);
      });
    },
    // 选择框内容变化
    handleChange(value) {
      // v-model绑定selectValueDefaultLabel 其实是绑定多选框中的input框中初始化的内容
      // 修改后 会对应将selectValueDefaultLabel改为value值 但是依然不影响显示 显示label 赋值value
      console.log("selectValueDefaultLabel", this.selectValueDefaultLabel);
      this.timeDate = value;
      this.SimulatedFloodControlOperation(value);
    },
    handleClickRain(e) {
      var p = e.target;
      // console.log("e",e)
      if (p instanceof T.Marker) {
        //  通过当前点击的 经纬度 找到ID 并把ID 传出去
        // console.log( "11",p.getLngLat().lng,p.getLngLat().lat,this.rainData)
        this.rainData.forEach((item) => {
          if (
            p.getLngLat().lng == item.longitude &&
            p.getLngLat().lat == item.latitude
          ) {
            this.$emit("handleClickRain", e, item.id);
          }
        });
      } else {
        alert("无法获知该覆盖物类型");
      }
    },
    handleClickRiver(e) {
      var p = e.target;
      if (p instanceof T.Marker) {
        this.riverData.forEach((item) => {
          if (p.getLngLat().lng == item.longitude) {
            this.$emit("handleClickRiver", e, item.id);
          }
        });
      } else {
        alert("无法获知该覆盖物类型");
      }
    },

    // 点击模拟防洪按钮
    async SimulatedFloodControlOperation(timeDate = 202106) {
      const { data: res } = await this.$http.get(
        `/api/emulation/basicinfo?date=${timeDate}`
      );
      // console.log(res);
      this.floodControlOperation.content = `当3小时面降雨量: ${res.data.riverFlowData[0]}毫米, ${res.data.riverFlowData[1]}毫米, ${res.data.riverFlowData[2]}毫米\n缙云河道3小时内流量 :${res.data.surfaceRainfallData[0]}立方米,${res.data.surfaceRainfallData[1]}立方米, ${res.data.surfaceRainfallData[2]}立方米`;
      this.visible = true;
      this.floodControlOperation.riverList.forEach((target) => {
        this.riverData.forEach((item) => {
          if (target.name == item.name) {
            target.limited = item.maxBlockingFlow;
          }
        });
      });
      // console.log("river", this.riverData);
      // 打开模态 关闭E-chart图表
      this.closeChart();
    },

    // 下载完整数据
    uploadFloodData() {
      // const {data:res} = await this.$http.get("api/download/historyFlowData")
      window.open(
        "http://flood-control-emulate.rexhub.space/api/download/historyFlowData",
        "_blank"
      );
    },
    // 下载三小时的数据
    uploadThreeFullyData() {
      window.open(
        `http://flood-control-emulate.rexhub.space/api/download/data3hours?date=${this.timeDate}`,
        "_blank"
      );
    },
    watchVisible(oldValue, newValue) {
      console.log("Visible", oldValue, newValue);
      if (!newValue) {
        //新值是false
        this.floodControlOperation.riverList.map((item, index, arr) => {
          arr[index].value = 0;
        });
        this.resultVolume = 0; // 最后为多少立方米
        this.reduceVolume = 0;
        this.occupyTotally = 0;
        this.selectValueDefaultLabel = "2021年6月洪水"; //多选框设置为初始状态值
        this.resultAllow = "true";
        this.timeDate = 202106;
        this.preBlockFlow = 0;
      }
    },
    closeChart(e) {
      console.log(e.lnglat.lat, e.lnglat.lng);
      this.$emit("closeChart", e);
    },
  },
  watch: {
    visible: "watchVisible",
  },
};
</script>
<style scoped>
body,
html {
  width: 100%;
  height: 100%;
  margin: 0;
  font-family: "Microsoft YaHei";
}
.basisWord {
  height: 40px;
}
#mapDiv {
  width: 100%;
  height: calc(100vh - 50px);
}
.btns {
  margin-right: 40px;
  position: absolute;
  bottom: 10px;
  right: 0;

  z-index: 999;
}
div /deep/ .ant-modal-footer {
  display: none;
}
div /deep/ .ant-input-number-input {
  text-align: center;
}
div /deep/ .ant-modal-body {
  padding: 12px;
}
.warnWord {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.success {
  margin-top: -10px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
input,
b,
p {
  margin-left: 5px;
  font-size: 14px;
}
.CenterContentPart {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  border-bottom: 1px solid #e8e8e8;
  padding-bottom: 10px;
  color: #000;
}
.ContentLayout {
  display: flex;
  align-items: center;
  justify-content: center;
}
div /deep/ .ant-modal-title {
  display: flex;
  justify-content: center;
  align-content: center;
  font-size: 20px;
}
.CenterContentPart:last-child {
  border-bottom: none;
}
div /deep/.ant-select-selection--single .ant-select-selection__rendered {
  width: 168px;
}
div /deep/.ant-modal {
  top: 50px;
}
.warnDescription {
  color: red;
  font-size: 20px;
  font-weight: 550;
}
</style>
